package jude.java.money.ant;

import java.io.File;
import java.util.ArrayList;

import org.apache.tools.ant.BuildException;

public class Random extends Base {

	private String type;
	private String property;
	private String param1;
	private String param2;
	private String value;
	
	public void setType(String type) {
		this.type = isEmpty(type) ? null : type.toLowerCase();
	}
	public void setProperty(String property) {
		this.property = property;
	}
	public void setParam1(String param1) {
		this.param1 = param1;
	}
	public void setParam2(String param2) {
		this.param2 = param2;
	}
	
	@Override
	public void execute() throws BuildException {
		if ("string".equals(type)) {
			
		} else if ("number".equals(type)) {
			int min = toInteger(param1);
			int max = toInteger(param2);
			int v = random(min, max + 1);
			value = String.valueOf(v);
		} else if ("path".equals(type)) {
			File f = new File(param1);
			if (!f.isAbsolute()) {
				param1 = getProject().getBaseDir() + "\\" + param1;
				f = new File(param1);
			}
			if (f.exists() && f.isDirectory()) {
				ArrayList<String> a = new ArrayList<String>();
				File[] fs = f.listFiles();
				boolean file = isEmpty(param1) || "file".equals(param2);
				boolean dir = isEmpty(param2) || "folder".equals(param2);
				for (int i = 0; i < fs.length; i++) {
					String name = fs[i].getName();
					if (name.startsWith("."))
						continue;
					if (file && fs[i].isFile())
						a.add(name);
					if (dir && fs[i].isDirectory())
						a.add(name);
				}
				if (a.isEmpty())
					return;
				int i = random(0, a.size());
				value = a.get(i);
			}
		}
		getProject().setProperty(property, value);
	}
	
	/***
	 *  min to max-1
	 */
	public static int random(int min, int max) {
		if (max < min) {
			int t = max;
			max = min;
			min = t;
		}
		java.util.Random r = new java.util.Random();
		return r.nextInt(max - min) + min;
	}
	
	public static int toInteger(String str) {
		try {
			return Integer.parseInt(str);
		} catch (NumberFormatException e) {
		}
		return 0;
	}
	
	public static void main(String[] args) {
		Random r = new Random();
		r.setType("number");
		r.setParam1("10");
		r.setParam2("12");
		r.setProperty("name");
		r.execute();
		System.out.println(r.value);
	}
}
